import base64
import hmac
import json
from datetime import datetime, timedelta
from app.config.oss_config import OssConfig
class MpUploadOssHelper:
    default_options={
        "accessKeyId": OssConfig().accessKeyId,
        "accessKeySecret": OssConfig().access_key_secretZ,
        "timeout": 1, # 限制参数的生效时间(单位：小时)。
        "maxSize": 50, # 限制上传文件大小(单位：MB)。
    }
    def __init__(self, options=None):
        if options is None:
            options=self.default_options
        self.access_key_id = options['accessKeyId']
        self.access_key_secret = options['accessKeySecret']
        self.timeout = options.get('timeout', 1)  # 默认1小时
        self.max_size = options.get('maxSize', 10)  # 默认10MB

    def create_upload_params(self):
        policy_base64 = self.get_policy_base64()
        signature = self.signature(policy_base64)
        return {
            'OSSAccessKeyId': self.access_key_id,
            'policy': policy_base64,
            'signature': signature,
        }

    def get_policy_base64(self):

        from datetime import datetime, timedelta

        # Get the current local time
        localtime = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        # Add one hour
        new_localtime = (datetime.strptime(localtime, "%Y-%m-%d %H:%M:%S") + timedelta(hours=1)).strftime("%Y-%m-%d %H:%M:%S")

        # Convert the new local time to UTC
        utctime = datetime.strptime(new_localtime, "%Y-%m-%d %H:%M:%S").astimezone(tz=None).strftime("%Y-%m-%dT%H:%M:%SZ")
        
        policy_text = {
            'expiration': utctime,
            'conditions': [
                ['content-length-range', 0, self.max_size * 1024 * 1024],
            ],
        }
        print(policy_text)
        policy_buffer = json.dumps(policy_text).encode('utf-8')
        return base64.b64encode(policy_buffer).decode('utf-8')

    def signature(self, policy):
        return base64.b64encode(
            hmac.new(self.access_key_secret.encode('utf-8'), policy.encode('utf-8'), 'sha1').digest()
        ).decode('utf-8')